package main

import (
	"fmt"
	"io"
	"log"
	"net"
	"zinxp/znet"
)

func main() {
	listener, err := net.Listen("tcp", "0.0.0.0:7878")
	if err != nil {
		log.Println("server listen error ", err)
		return
	}

	for {
		conn, err := listener.Accept()
		if err != nil {
			log.Println("Server accept error ", err)
		}

		go func(conn net.Conn) {
			dp := znet.NewDataPack()
			for {
				headData := make([]byte, dp.GetHeadLen())//len=8 头长度是8
				_, err := io.ReadFull(conn, headData)
				if err != nil {
					log.Println("read head error ",err)
					break
				}
				//将headData字节流，拆包到msg中
				msgHead, err := dp.Unpack(headData)
				if err != nil {
					log.Println("server unpack error ", err)
					return
				}

				if msgHead.GetDataLen() > 0 {
					//msg 是有data数据的，需要再次读取data数据
					msg := msgHead.(*znet.Message)
					msg.Data = make([]byte, msg.GetDataLen())
					_, err := io.ReadFull(conn, msg.Data)
					if err != nil {
						log.Println("server unpack data error ", err)
						return
					}
					fmt.Println("==>Recv Msg: ID=", msg.Id, " len=", msg.DataLen, " data=", string(msg.Data))
				}
			}
		}(conn)
	}
}
